<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Refund extends Eloquent
{
	use SoftDeletingTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'customer_payment';
	protected $validator = null;

	public function saveData($data){
		$refund = new Refund;

		if(isset($data['id'])){
			$refund = Refund::firstOrCreate(array('id' => $data['id']));
		}

		$refund->customer = $data['customer'];
		$refund->total    = $data['total'];
		$refund->date     = $data['date'];
		$refund->type     = 'refund';

		$refund->save();

		return $refund;
	}

	public function getAll($type){
		$customers = Customer::whereType($type)->orderBy('name')->get();
		$result = array();

		foreach($customers as $customer){
			$result[$customer->id]['name'] = $customer->name;

			$refund = DB::table('customer_payment')
							->whereCustomer($customer->id)
							->whereNull('deleted_at')
							->whereType('refund')
							->sum('total');

			$result[$customer->id]['refund'] = $refund;
		}

		return $result;
	}

	public function getDetail($customer){
		$result = DB::table('customer_payment')
							->whereNull('deleted_at')
							->whereType('refund')
							->whereCustomer($customer)
							->select('id', 'total', 'date', 'order')
							->orderBy('date', 'DESC')
							->get();

		return $result;
	}
}